package com.kuang.demo02;

import java.util.concurrent.locks.ReentrantLock;

/**lock锁
 * @author FHL
 */
public class TestLock {
    public static void main(String[] args) {
BuyTicket buyTicket=new BuyTicket();
new Thread(buyTicket,"丽水").start();
new Thread(buyTicket,"愉快").start();
new Thread(buyTicket,"亚楠").start();
    }
    static class BuyTicket implements Runnable{
        //定义一个锁，为了让其安全，使用private修饰
      private final   ReentrantLock lock=new ReentrantLock();
        private int ticketNumber=10;
        @Override
        public void run() {
            //加锁
            lock.lock();
            try {
                while (true){
                    if (ticketNumber>0){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName()+ticketNumber--);
                    }else {
                        break;
                    }
                }
            }finally {
                //解锁
                lock.unlock();
            }
        }
    }
}
